package com.how2java.controller;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.builder.xml.dynamic.WhereSqlNode;
import org.apache.taglibs.standard.tag.common.xml.WhenTag;
import org.junit.experimental.theories.FromDataPoints;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
import com.how2java.util.Page;

// 告诉spring mvc这是一个控制器类
@Controller
@RequestMapping("")
public class CategoryController {
	@Autowired
	CategoryService categoryService;

	@RequestMapping(value="/category",method=RequestMethod.GET)
	public ModelAndView listCategory(Page page){
		ModelAndView mav = new ModelAndView();
		List<Category> cs= categoryService.list(page);
		int total = categoryService.total();
		page.caculateLast(total);
		// 放入转发参数
		mav.addObject("cs", cs);
		// 放入jsp路径
		mav.setViewName("listCategory");
		System.out.println("mav:------------->>"+mav);
		return mav;
	}
	
	@RequestMapping(value="/category",method=RequestMethod.PUT)
	public ModelAndView addCategory(Category category){
		System.out.println("category.getName():"+category.getName());
		categoryService.add(category);
		ModelAndView mav = new ModelAndView("redirect:/category");
	    return mav;
	}	
	
	@RequestMapping(value="/category/{id}",method=RequestMethod.DELETE)
	public ModelAndView deleteCategory(Category category){
		categoryService.delete(category);
		ModelAndView mav = new ModelAndView("redirect:/category");
		return mav;
	}	
	@RequestMapping(value="/category/{id}",method=RequestMethod.GET)
	public ModelAndView editCategory(Category category){
		Category c= categoryService.get(category.getId());
		ModelAndView mav = new ModelAndView("editCategory");
		mav.addObject("c", c);
		return mav;
	}	
	@RequestMapping(value="/category/{id}",method=RequestMethod.POST)
	public ModelAndView updateCategory(Category category,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		System.out.println("------------>>>"+category);
		System.out.println("name------------>>>"+req.getParameter("name"));
		resp.setContentType("text/html;charset=utf-8");
		categoryService.update(category);
		ModelAndView mav = new ModelAndView("redirect:/category");
		return mav;
	}	

}
